let bcrypt = require('bcryptjs')
const { userFormatError, userAlreadyExisted, userDoesNotExist, invalidPassword } = require('../consisitant/err.type')
const { getUserInfo } = require('../service/user.service')

const userValidator = async (ctx, next) => {
    const { user_name, password } = ctx.request.body
    if (!user_name || !password) {
        ctx.app.emit('error', userFormatError, ctx)
        return
    }
    await next()
}

const verifyUser = async (ctx, next) => {
    const { user_name } = ctx.request.body
    if (await getUserInfo({ user_name })) {
        ctx.app.emit('error', userAlreadyExisted, ctx)
        return
    }
    await next()
}

const cryptPassword = async (ctx, next) => {
    let { password } = ctx.request.body
    let salt = bcrypt.genSaltSync(10)
    let hash = bcrypt.hashSync(password, salt)
    ctx.request.body.password = hash
    await next()
}

const verifyLogin = async (ctx, next) => {
    const { user_name, password } = ctx.request.body
    const res = await getUserInfo({ user_name })
    if (!res) {
        ctx.app.emit('error', userDoesNotExist, ctx)
        return
    }
    if (!bcrypt.compareSync(password, res.password)) {
        ctx.app.emit('error', invalidPassword, ctx)
        return
    }
    await next()
}

module.exports = {
    userValidator,
    verifyUser,
    cryptPassword,
    verifyLogin
}
